package com.example.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.example.dao.FactorOptionRepository;
import com.example.dao.FactorRepository;
import com.example.dao.InsuranceFormRepository;
import com.example.dao.InsuranceRepository;
import com.example.dao.PolicyFactorRepository;
import com.example.dao.ProductRepository;
import com.example.dao.SubInsuranceDetailRepository;
import com.example.dao.UserDao;
import com.example.entity.Factor;
import com.example.entity.FactorOption;
import com.example.entity.Insurance;
import com.example.entity.InsuranceForm;
import com.example.entity.Product;
import com.example.service.FactorHandleService;
import com.example.service.ProductCenterService;

@Controller
public class ProductCenterController extends WebMvcConfigurerAdapter implements ApplicationContextAware{
	@Autowired
	private UserDao userDao;
	@Autowired
	private ProductRepository productDao;
	@Autowired
	private FactorRepository factorDao;
	@Autowired
	private FactorOptionRepository factorOptionDao;
	@Autowired
	ProductCenterService productCenterService;
	@Autowired
	InsuranceRepository insuranceDao;
	@Autowired
	InsuranceFormRepository insuranceFormDao;
	@Autowired
	SubInsuranceDetailRepository subInsuranceDetail;
	@Autowired
	PolicyFactorRepository policyFactorDao;
	@Autowired
	FactorHandleService factorHandleService;
	
	 private final Logger logger = LoggerFactory.getLogger(this.getClass());  
	
	
	@RequestMapping("/")
	public String index()throws Exception{
		return "index";
	}
	/**进入创建因子页面**/
	@RequestMapping("/createFactor")
	public String createFactor()throws Exception{
		return "pc/createFactor";
	}
	/**增加因子**/
	@RequestMapping("/addFactor")
	public String addFactor(Factor factor){
		Factor newFactor=factorDao.save(factor);
		if(factor.getFactorDataType().equals("2")){
			for(FactorOption one:factor.getFactorOptions()){
				one.setFactorId(newFactor.getId());
				one.setCoName(newFactor.getCoName());
				one.setCtName(newFactor.getCtName());
				factorOptionDao.save(one);
			}
		}
		return "index";
	}
	/**进入创建产品界面**/
	@RequestMapping("/conf")
	public String conf(){
		return "pc/conf";
	}
	/**保存产品，进入险种界面**/
	@RequestMapping("/configInsurance")
	public String toInsurance(Product product,HttpServletRequest request){
		productDao.save(product);
		request.setAttribute("productId", product.getId());
		
		List<Factor>feeList=factorDao.findByFeeOrfacotr("1");
		request.setAttribute("feeList", feeList);
		List<Factor>factorList=factorDao.findByFeeOrfacotr("2");
		request.setAttribute("factorList", factorList);
		return "pc/configInsurance";
	}
	/**校验产品名称唯一性**/
	@RequestMapping("/uniqueProductName")
	@ResponseBody
	public Map<String,String> uniqueProductName(HttpServletRequest request,String name)throws Exception{
		logger.error("This is a logger error message");  
		logger.debug("This is a logger debug message");  
		logger.info("This is a logger info message");  
		logger.warn("This is a logger warn message");  
		List<String> list = productDao.findAllProductName();
		Map<String,String> map=new HashMap<String,String>();
		if(list.contains(name)){
			map.put("contains", "1");
		}else{
			map.put("contains", "0");
		}
		return map;
		
	}
	/**校验因子名称唯一性**/
	@RequestMapping("/uniqueFactorName")
	@ResponseBody
	public Map<String,String> uniqueFactorName(HttpServletRequest request,String name)throws Exception{
		List<String> list = factorDao.findAllProductName();
		Map<String,String> map=new HashMap<String,String>();
		if(list.contains(name)){
			map.put("contains", "1");
		}else{
			map.put("contains", "0");
		}
		return map;
		
	}
	/**创建险种**/
	@RequestMapping("/createInsurance")
	public String createInsurance(Insurance insurance,HttpServletRequest request)throws Exception{
		long productId = insurance.getProductId();
		
		String formula[]=productCenterService.createCalculator(request);
		
		insurance.setFormula(formula[0]);
		insurance.setFormulaDesc(formula[1]);
		
		insuranceDao.save(insurance);
		
		request.setAttribute("insurance", insurance);
		request.setAttribute("productId", productId);

		return "pc/configCalculator";
	}
	/**前天更新计算公式**/
	@RequestMapping("/changeFormula")
	@ResponseBody
	public Map<String ,String>changeFormula(String name){
		Map<String,String >map=new HashMap<>();
		String result=name.replace("?", "").replace("$", "").replace("*", "X");
		map.put("success", "1");
		map.put("result",result);
		return map;
	}
	/**更新险种算法**/
	@RequestMapping("/updateCalculator")
	public String updateCalculator(Insurance insurance,HttpServletRequest request)throws Exception{
		long productId = insurance.getProductId();
		request.setAttribute("productId", productId);
		String calFormula = insurance.getCalFormula();
		String formulaDesc = insurance.getFormulaDesc();
		long id = insurance.getId();
		insuranceDao.setCalculator(calFormula,formulaDesc,id);
		
		String nextPath=request.getParameter("continue");
		if("on".equals(nextPath)){
			List<Factor>feeList=factorDao.findByFeeOrfacotr("1");
			request.setAttribute("feeList", feeList);
			List<Factor>factorList=factorDao.findByFeeOrfacotr("2");
			request.setAttribute("factorList", factorList);
			return "pc/configInsurance";
		}else{
			return "index";
		}
	}
	
	/**进入投保页面,选择产品**/
	@RequestMapping("/insurance")
	public String insurance(HttpServletRequest request){
		List<Product>productList=productDao.findAll();
		request.setAttribute("productList", productList);
		return "pc/insurance";
	}
	/**进入投保详情页面**/
	@RequestMapping("/toInsuranceDetail")
	public String toInsuranceDetail(HttpServletRequest request,Product product)throws Exception{
		Long productId=product.getId();
		if(null==productId){
			throw new RuntimeException("没有找到对应的保险产品");
		}
		
		product = productCenterService.findProductDetail(product);
		request.setAttribute("productResult", product);
		//获取所有险种可能的最大因子数，方便后面操作中后台获取前端所有因子的下标
		Integer maxFactorNum=0;
		for(Insurance one:product.getInsuranceList()){
			if(one.getFactors().length>maxFactorNum){
				maxFactorNum=one.getFactors().length;
			}
		}
		request.setAttribute("maxFactorNum", maxFactorNum);
		
		return "pc/insuranceDetail";
	}
	/**保费计算**/
	@RequestMapping("/calculatePremium")
	public String calculate(HttpServletRequest request,InsuranceForm form)throws Exception{
		Product product = productDao.findById(form.getProductId());
		form.setProductName(product.getProductName());
		productCenterService.sortFactor(form);
		productCenterService.calculate(form);
		request.setAttribute("form", form);
		productCenterService.saveForm(form);
		return "pc/preview";
	}
	/**查看第一步：进入选择产品页面	 */
	@RequestMapping("/insuranceListStep1")
	public String insuranceListStep1(HttpServletRequest request){
		List<Product> product = productDao.findAll();
		request.setAttribute("product", product);
		return "pc/show/productList";
	}
	/**查看第二步：进入选择产品下的投保单页面	 */
	@RequestMapping("/insuranceListStep2")
	public String insuranceListStep2(HttpServletRequest request,Product product){
		List<InsuranceForm>list=insuranceFormDao.findByProductId(product.getId());
		request.setAttribute("list", list);
		return "pc/show/insuranceList";
	}
	/**进入批单页面*/
	@RequestMapping("/toEndorSelection")
	public String toEndorSelection(HttpServletRequest request,BigDecimal id){
		int a=1;
		a=2;
		return null;
	}
	
	private ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
	}
	
	
	
}














